package com.insight.modules.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.insight.common.message.websocket.WebSocket;
import com.insight.modules.system.entity.SysAnnouncementSend;
import com.insight.modules.system.mapper.SysAnnouncementSendMapper;
import com.insight.modules.system.model.AnnouncementSendModel;
import com.insight.modules.system.service.ISysAnnouncementSendService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 用户通告阅读标记表
 * @Author: jeecg-boot
 * @Date:  2019-02-21
 * @Version: V1.0
 */
@Service
public class SysAnnouncementSendServiceImpl extends ServiceImpl<SysAnnouncementSendMapper, SysAnnouncementSend> implements ISysAnnouncementSendService {

	@Resource
	private SysAnnouncementSendMapper sysAnnouncementSendMapper;

	/**
	 * 根据用户ID查询公告发送记录的消息ID列表
	 * @param userId 用户ID
	 * @return 公告ID列表
	 */
	@Override
	public List<String> queryByUserId(String userId) {
		return sysAnnouncementSendMapper.queryByUserId(userId);
	}

	/**
	 * 分页查询当前用户的公告发送记录
	 * @param page 分页参数
	 * @param announcementSendModel 查询条件封装模型
	 * @return 分页后的公告发送记录列表
	 */
	@Override
	public Page<AnnouncementSendModel> getMyAnnouncementSendPage(Page<AnnouncementSendModel> page,
																 AnnouncementSendModel announcementSendModel) {
		// 调用mapper方法查询分页数据，并设置到Page对象中返回
		return page.setRecords(sysAnnouncementSendMapper.getMyAnnouncementSendList(page, announcementSendModel));
	}

	/**
	 * 根据公告ID获取已发送的用户ID列表
	 * @param announcementId 公告ID
	 * @return 发送该公告的用户ID列表
	 */
	@Override
	public List<String> getSendUserIdByAnnouncementId(String announcementId) {
		return super.baseMapper.getSendUserIdByAnnouncementId(announcementId);
	}

	/**
	 * 通过 WebSocket 向指定公告的接收用户推送消息
	 * @param anntId 公告ID
	 * @param messageType 消息类型
	 * @param data 发送的数据对象
	 */
	@Override
	public void senderMsg(String anntId, String messageType, Object data) {
		// 获取该公告已发送用户的ID列表
		List<String> userIds = super.baseMapper.getSendUserIdByAnnouncementId(anntId);
		// 构造消息体，包含消息类型和具体数据
		JSONObject jsonOut = new JSONObject();
		jsonOut.put("messageType", messageType);
		jsonOut.put("data", data);
		// 使用 WebSocket 群发消息
		WebSocket.sendMoreMessage(userIds.toArray(new String[0]), jsonOut.toJSONString());
	}
}

